<?php

define('WORKFLOW_ACTION', 1);
define('WORKFLOW_STATUS', 2);

/**
 * get swimlane list
 */
function get_swimlane_list($swimlane_list = array()) {
  // print_r($_SESSION);
//  if(empty($swimlane_list)){    
//    $swimlane_list = isset($_SESSION['workflow_return']['swimlaneList']) ? $_SESSION['workflow_return']['swimlaneList']:'';   
//  }   
  $swimlanes = array();
  if ($swimlane_list) {
    foreach ($swimlane_list as $v) {
      $swimlanes[$v['swimlaneKey']] = array(
          'swimlaneKey' => $v['swimlaneKey'],
          'swimlaneName' => $v['swimlaneName'],
          'initate_falg' => $v['initateSwimlaneFlag'],
      );
    }
  }
  return $swimlanes;
}

function get_user_role_list() {
  $roles = user_roles(TRUE);
  unset($roles[DRUPAL_ANONYMOUS_RID]);
  unset($roles[DRUPAL_AUTHENTICATED_RID]);
  return $roles;
}

function get_role_by_swimlane($workflow_id, $swimlane_id) {
  return array();
}

function get_transition_list($transition_list = array()) {
//   if(empty($swimlane_list)){
//    $transition_list = isset($_SESSION['workflow_return']['transitionList'])?$_SESSION['workflow_return']['transitionList']:'';
//  }
  $transitions = array();
  if ($transition_list) {
    foreach ($transition_list as $k => $v) {
      $transitions[$v['transitionId']] = array(
          'transitionName' => $v['transitionName'],
          'statusCode' => $v['statusCode'],
      );
    }
  }
  return $transitions;
}

function get_action_status_by_transition($condition) {
  $result = '';
  //$wf_private_process_def_id, $trans_key, $status_code
  //workflow_trans_action_status_mapping
  $query = db_select('workflow_trans_action_status_mapping', 'asm')->fields('asm');
  foreach ($condition as $field => $value) {
    $query->condition($field, $value);
  }
//  $query->condition('asm.wf_private_process_def_id', $wf_private_process_def_id);
//  $query->condition('asm.trans_key', $trans_key);
//  $query->condition('asm.status_code', $status_code);
  $result = $query->execute()->fetchAllAssoc('trans_key', PDO::FETCH_ASSOC);
  return $result;
}

/**
 * get swimlan keys for tasklist api
 */
function get_swimlanes_by_role($user, $condition = array()) {
  if (empty($user)) {
    global $user;
  }
  $query = db_select('workflow_swimlane_role_mapping', 'srm')->fields('srm');
  $rids = array_keys($user->roles);
  $query->condition('srm.rid', $rids, 'IN');
  foreach ($condition as $field => $value) {
    $query->condition($field, $value);
  }
  $result = $query->execute()->fetchAll(); //print_r($result);die;//('swimlane_key', PDO::FETCH_ASSOC);
  $role = array();
  if ($result) {
    foreach ($result as $val) {
      $role[] = $val->swimlane_key . ':' . $val->wf_private_process_def_id;
    }
  }
  return array_unique($role);
  //return array('BasicInitiationWorkflow1_HRLevel1');
}

function get_initate_swimlane_by_role($user=''){
   if (empty($user)) {
    global $user;
  }
  $query = db_select('workflow_swimlane_role_mapping', 'srm')->fields('srm');
  $rids = array_keys($user->roles);
  $query->condition('srm.rid', $rids, 'IN');
  $query->condition('srm.initate_flag',1);
  $result = $query->execute()->fetchAllAssoc('wf_private_process_def_id', PDO::FETCH_ASSOC);
  return $result;
}

function get_swimlanes_by_wf_private_process_def_id($wf_private_process_def_id) {
  $query = db_select('workflow_swimlane_role_mapping', 'srm')->fields('srm');
  $query->condition('wf_private_process_def_id', $wf_private_process_def_id);
  $result = $query->execute()->fetchAll();
  foreach ($result as $v) {
    $return[$v->swimlane_key][] = $v->rid;
  }
  return $return;
}

function get_transition_action_status_by_wf_private_process_def_id($wf_private_process_def_id) {
  $query = db_select('workflow_trans_action_status_mapping', 'wtasm')->fields('wtasm');
  $query->condition('wf_private_process_def_id', $wf_private_process_def_id);
  $result = $query->execute()->fetchAllAssoc('trans_key', PDO::FETCH_ASSOC);
  foreach ($result as $trans_key => $v) {
    $return[$trans_key][] = $v;
  }
  return $return;
}

function get_workflow_thumb($workflow_id) {
  return 'workflow_thumb_' . $workflow_id . '.png';
}

function swimlane_role_config_save($wf_private_process_def_id, $values) {
  foreach ($values['swimlane_key'] as $swimlane_key) {
    foreach ($values['role'][$swimlane_key] as $rid) {
      $row = array(
          'swimlane_key' => $swimlane_key,
          'wf_private_process_def_id' => $wf_private_process_def_id,
          'rid' => $rid,
          'initate_flag' => $values['initate_flag'][$swimlane_key],
      );
      drupal_write_record('workflow_swimlane_role_mapping', $row);
    }
  }
  // drupal_write_record('swimlane_role_mapping', $data);  
}

function transition_action_status_config_save($wf_private_process_def_id, $values) {
  foreach ($values['trans_key'] as $trans_key) {
    $row = array(
        'wf_private_process_def_id' => $wf_private_process_def_id,
        'trans_key' => $trans_key,
        'action_name' => $values['action_name'][$trans_key],
        'status_code' => $values['status_code'][$trans_key],
        'status' => $values['status'][$trans_key],
    );
    //print_r($row);
    drupal_write_record('workflow_trans_action_status_mapping', $row);
    //  $data[]=$row;
  }
  // drupal_write_record('trans_action_status_mapping', $data);  
}

function workflow_process_config_save($wf_private_process_def_id, $workflow_unique) {
  global $user;
  $data = array(
      'wf_private_process_def_id' => $wf_private_process_def_id,
      'workflow_unique' => $workflow_unique,
      'condition' => '', //$condition,
      'uid' => $user->uid,
      'updated' => REQUEST_TIME,
      'created' => REQUEST_TIME,
  );
  /*
    if (count(get_process_mapping_by_workflow_unique($workflow_unique)) > 0) {
    unset($data['created']);
    }
   */
  drupal_write_record('workflow_process_mapping', $data);
}

function get_process_mapping_by_workflow_unique($workflow_unique) {
  if (!empty($workflow_unique)) {
    $query = db_select('workflow_process_mapping', 'pwm')->fields('pwm', array('wf_private_process_def_id'));
    $query->condition('workflow_unique', $workflow_unique);
    $query->orderBy('created', 'DESC');
    $result = $query->execute()->fetchField();
    //$result = $result['wf_private_process_def_id'];
    return $result;
  } else {
    return '';
  }
}

function get_process_mapping_by_workflow_unique_arr($workflow_unique) {
  if (!empty($workflow_unique)) {
    $query = db_select('workflow_process_mapping', 'pwm')->fields('pwm');
    $query->condition('workflow_unique', $workflow_unique);
    $query->orderBy('created', 'DESC');
    $query->orderBy('updated', 'DESC');
    $result = $query->execute()->fetchAllAssoc('wf_private_process_def_id', PDO::FETCH_ASSOC);
    //$result = $result['wf_private_process_def_id'];
    return $result;
  } else {
    return array();
  }
}

function get_process_mapping_by_wf_private_def_id($wf_private_def_id) {
  if (!empty($wf_private_def_id)) {
    $query = db_select('workflow_process_mapping', 'pwm')->fields('pwm', array('wf_private_process_def_id'));
    $query->condition('wf_private_def_id', $wf_private_def_id);
    $query->orderBy('created', 'DESC');
    $query->orderBy('updated', 'DESC');
    $result = $query->execute()->fetchField();
    //$result = $result['wf_private_process_def_id'];
    return $result;
  } else {
    return '';
  }
}



function workflow_goback($form, &$form_state) {
  // print_r($form_state);
  // exit;
  global $base_url;
  global $user;
  $logout_url = $base_url . '/caslogout';
  $user_url = $base_url . '/user';

  $node = node_load($form_state['values']['nid']);
  $workflow_return = get_workflow_return_data($node);
  $workflow_unique = 'WORK_CONFIG_DATA'.$workflow_return['privateProcessDefId'];
  
    unset($form_state['values']['form_build_id']);
    unset($form_state['values']['form_token']);
    unset($form_state['values']['op']);
    $_SESSION[$workflow_unique]=$form_state['values'];
   
  $get_data = array(
      'systemCode' => $workflow_return['systemCode'],
      'moduleCode' => $workflow_return['moduleCode'],
      'uniqueCode' => $workflow_return['uniqueCode'],
      'privateProcessDefId' => $workflow_return['privateProcessDefId'],
      'swimlaneConfigUrl' => $form_state['swimlane_config_url'],
      'workflowConfigurationSource' => $form_state['workflow_config_source_url'],
      'logoutUrl' => urlencode($logout_url),
      'userName' => $user->name,
      'userUrl' => urlencode($user_url),
  );
  $form_state['redirect'] = $workflow_return['workflowConfigurationSource'] . '?' . http_build_query($get_data);
}

function webform_workflow_return($node) {
  //file_put_contents(DRUPAL_ROOT.'/log.txt', var_export($_REQUEST,true));
  $data = isset($_REQUEST['requestJSON']) ? $_REQUEST['requestJSON'] : '';
  $data = json_decode($data, true);

  if (!empty($data)) {
    variable_set('workflow_return_' . $node->nid, $data);
  }
  //print_r($_SESSION);

  /* $record=array(
    'wf_private_process_def_id'=>$wf_private_process_def_id,
    'data'=>$data,
    );
   */
  // drupal_write_record('workflow_return', $record);
  drupal_goto('node/' . $node->nid . '/swimlane');
}

function get_workflow_return_data($node) {
  // $data=isset($_SESSION['workflow_return'])?$_SESSION['workflow_return']:'';
  $data = variable_get('workflow_return_' . $node->nid);

  $data['swimlane_list'] = get_swimlane_list($data['swimlaneList']);
  $data['trans_keys'] = get_transition_list($data['transitionList']);

  return $data;
}

/*
 * get workflow unique by node
 * add by kale @2013-02-20
 */

function get_workflow_unique(&$node) {
  //$module_code=$node->field_form_type['und'][0]['value'];
  $module_code = 'if';
  $workflow_unique = SYSTEM_CODE . '_' . $module_code . '_' . $node->nid;
  $node->workflow_unique = $workflow_unique;
  $node->module_code = $module_code;
  return $workflow_unique;
}

/*
 * get instance info
 * add by kale @2013-02-21
 */

function get_instance_info(&$node, &$submission) {
  if ($submission->is_draft == 1) {
    return;
  }
  $sid = $submission->sid;
  $query = db_select('workflow_instance_entity_mapping', 'em')->fields('em');
  //$query->leftJoin('workflow_trans_action_status_mapping','asm','em.status_code=asm.status_code AND asm.wf_private_process_def_id=em.wf_private_process_def_id');
  // $query->fields('asm');  
  $query->condition('em.entity_id', $sid);
  $result = $query->execute()->fetchAllAssoc('entity_id', PDO::FETCH_ASSOC);
  $node->wf_private_process_def_id = $result[$sid]['wf_private_process_def_id'];
  $submission->instance_id = $result[$sid]['instance_id'];
  $submission->trans_key = $result[$sid]['trans_key'];
  $submission->status_code = $result[$sid]['status_code'];
  get_submission_status($node, $submission);
  return $result;
}

function get_submission_status(&$node, &$submission) {
  $query = db_select('workflow_trans_action_status_mapping', 'asm');
  $query->fields('asm');
  $query->condition('asm.wf_private_process_def_id', $node->wf_private_process_def_id);
  $query->condition('asm.trans_key', $submission->trans_key);
  $result = $query->execute()->fetchAllAssoc('wf_private_process_def_id', PDO::FETCH_ASSOC);
  if (isset($result[$node->wf_private_process_def_id])) {
    $submission->status = $result[$node->wf_private_process_def_id]['status'];
  } else {
    //$submission->status = t('Draft');
  }
}

/*
 * cancel workflow config
 * add by kale @2013-02-22
 */

function cancel_workflow_config($form, &$form_state) {
  drupal_goto('node/' . $form_state['values']['nid'] . '/workflow_config');
}